package platform

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"net/http"
	"time"
	"token-centre/global"
	"token-centre/model"
)

// 获取/刷新 微信公众号 access_token
// 存入 数据库 跟缓存
func WeChatOfficialAccountsToken(PlateformName string, AppName string) {
	var one model.App

	if err := global.Db.Where("platform_name=? and name=?", PlateformName, AppName).First(&one).Error; err != nil {
		log.Fatal(err)
		return
	}

	var APPID = one.AppID
	var APPSECRET = one.AppSecret

	res, err := http.Get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID + "&secret=" + APPSECRET)

	if err != nil {
		log.Fatal(err)
		return
	}

	data, err := ioutil.ReadAll(res.Body)
	{
		res.Body.Close() //一定要记得关闭连接

		if err != nil {
			log.Fatal(err)
		}
	}

	var j struct {
		Access_token string `json:"access_token"`
		Expires_in   uint   `json:"expires_in"`
		Errcode      uint   `json:"errcode"`
		Errmsg       string `json:"errmsg"`
	}

	if json.Unmarshal(data, &j) != nil {
		log.Fatal(err)
		return
	}

	if j.Access_token == "" {
		log.Fatal(j)
		return
	}

	// 存入数据库
	one.Token = j.Access_token
	one.TokenExpire = time.Now().Add(time.Duration(j.Expires_in) * time.Second)
	if err := global.Db.Save(&one).Error; err != nil {
		log.Fatal(j)
		return
	}

	// 存入缓存
	var h = map[string]interface{}{
		"token":  one.Token,
		"expire": one.TokenExpire,
	}

	global.SetToken(PlateformName, AppName, h)
}
